package com.tongguan.paypos.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.basewin.aidl.OnPrinterListener;
import com.basewin.define.FontsType;
import com.basewin.services.PrinterBinder;
import com.basewin.services.ServiceManager;
import com.tongguan.paypos.R;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.entity.MoneyCount;
import com.tongguan.paypos.entity.TransInfo;
import com.tongguan.paypos.utils.Arith;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.PrintUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.view.CustomAlertDialog;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Joylive on 2016/12/17 .
 */

public class PrintDetailFragment extends BaseFragment {

    public static final String PRINT_DETAIL = "printDetail";
    public static final String PRINT_REPEAT = "printRepeat";

    @BindView(R.id.tv_merchant_name)
    TextView mTvMerchantName;
    @BindView(R.id.tv_merchant_id)
    TextView mTvMerchantId;
    @BindView(R.id.tv_terminal_no)
    TextView mTvTerminalNo;
    @BindView(R.id.tv_order_id)
    TextView mTvOrderId;
    @BindView(R.id.tv_trade_up_order)
    TextView mTvTradeUpOrder;
    @BindView(R.id.ll_up_order)
    LinearLayout mLlUpOrder;
    @BindView(R.id.tv_pay_type)
    TextView mTvPayType;
    @BindView(R.id.tv_trans_type)
    TextView mTvTransType;
    @BindView(R.id.tv_order_state)
    TextView mTvOrderState;
    @BindView(R.id.tv_trans_time)
    TextView mTvTransTime;
    @BindView(R.id.ll_order_money)
    LinearLayout mLlOrderMoney;
    @BindView(R.id.ll_coupon_money)
    LinearLayout mLlCouponMoney;
    @BindView(R.id.tv_trans_amount)
    TextView mTvTransAmount;
    @BindView(R.id.tv_trans_money)
    TextView mTvMoney;
    @BindView(R.id.tv_trans_coupon_money)
    TextView mTvCouponMoney;
    @BindView(R.id.button)
    Button mButton;

    private TransInfo mTransInfo;
    private boolean isCoupon = false;//是否优惠
    private MoneyCount mMoneyCount;
    private int index = 0;
    private PrinterListener mPrinterListener = new PrinterListener();
    private String repeatType;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_print_detail, container, false);
        ButterKnife.bind(this, rootView);
        setTitle("订单详情");
        Bundle extras = getArguments();
        if (extras != null) {
            mTransInfo = extras.getParcelable(PRINT_DETAIL);
            repeatType = extras.getString(PRINT_REPEAT);
            L.e("repeatType = " +repeatType);
            initView();
        }
        initEvent();
        return rootView;
    }

    private void initEvent() {
        mButton.setOnClickListener(v -> {
            if (mTransInfo != null) {
                if (!mDialog.isShowing()) {
                    mDialog.setLoadingMessage("打印中...");
                    mDialog.show();
                }
                mHandler.sendEmptyMessageDelayed(0, 500);
            }
        });
    }

    private void initView() {
        mTvMerchantName.setText(mTransInfo.getMerchantName());
        mTvMerchantId.setText(mTransInfo.getMerchantId());
        mTvTerminalNo.setText(mTransInfo.getPosId());
        mTvOrderId.setText(mTransInfo.getOrderId());
        //上游订单号 （会员卡和现金没有）
        if ("XJ".equals(mTransInfo.getChannelId()) || "HYC".equals(mTransInfo.getChannelId())) {
            mLlUpOrder.setVisibility(View.GONE);
        } else {
            mTvTradeUpOrder.setText(mTransInfo.getUpOrderId());
        }
        String payTypeText = AppConstants.getPayTypeText(mTransInfo.getChannelId());
        mTvPayType.setText(payTypeText);
        String state = mTransInfo.getState();
        mTvTransType.setText(AppConstants.transType.get(state));
        mTvOrderState.setText(AppConstants.orderState.get(state));
        mTvTransTime.setText(mTransInfo.getPayTime());
        double money = mTransInfo.getPayMoney();
        double coupon_money = mTransInfo.getCouponMoney();
        double amount;
        if (coupon_money > 0) {
            isCoupon = true;
            mLlOrderMoney.setVisibility(View.VISIBLE);
            mLlCouponMoney.setVisibility(View.VISIBLE);
            mTvMoney.setText(String.valueOf(money));
            String temp = "-" + coupon_money;
            mTvCouponMoney.setText(temp);
            amount = Arith.sub(money, coupon_money);
            mTvTransAmount.setText(String.valueOf(amount));
        } else {
            amount = money;
            mTvTransAmount.setText(String.valueOf(amount));
        }
        mMoneyCount = new MoneyCount(money, coupon_money, amount);
    }

    private boolean flag = false;
    private void printerResult(int printIndex){
        new Thread(() -> {
            try{
                String data = null;
                PrinterBinder printer = ServiceManager.getInstence().getPrinter();
                printer.setPrintGray(1500);
                printer.setPrintFont(FontsType.simsun);
                printer.cleanCache();
                if(PrintRandomFragment.REPEAT.equals(repeatType)){
                    flag = true;
                }
                data = PrintUtils.printOnlineOrder(mTransInfo, printIndex, isCoupon, mMoneyCount, flag);
                mPrinterListener.isRepeat = false;
                printer.print(data, null, mPrinterListener);
            }catch(Exception e){
                e.printStackTrace();
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!frmCtx.isFinishing()) {
                switch (msg.what) {
                    case 0: //延时打印
                        printerResult(index);
                        break;
                    case 1:
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        if (index == 0) {
                            new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                    .setMessage("请撕下票据")
                                    .setPositiveButton("打印下一联", (dialog, which) -> {
                                        if (mDialog != null && !mDialog.isShowing()) {
                                            mDialog.show();
                                        }
                                        index++;
                                        mHandler.sendEmptyMessageDelayed(0, 500);
                                    }).setNegativeButton("退出打印", (dialog, which) -> {
                            }).setTimer(true).show();
                        }
                        if (index == 1) {
                            index = 0;
                        }
                        break;
                    case 2: //打印异常重打印
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        String message = (String) msg.obj;
                        new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                .setMessage("异常 " + message)
                                .setPositiveButton("重新打印", (dialog, which) -> {
                                    if (mDialog != null && !mDialog.isShowing()) {
                                        mDialog.show();
                                    }
                                    mHandler.sendEmptyMessage(0);
                                }).setNegativeButton("退出", (dialog, which) -> {
                        }).show();
                        break;
                }
            }
        }
    };

    private class PrinterListener implements OnPrinterListener{
        boolean isRepeat = false;
        @Override
        public void onStart() {
            // TODO 打印开始
            L.d(" 打印开始");
        }

        @Override
        public void onFinish() {
            // TODO 打印结束
            L.d(" 打印结束");
            mHandler.sendEmptyMessage(1);
        }

        @Override
        public void onError(int errorCode, String detail) {
            // TODO 打印出错
            L.d(" 打印出错");
            if (!isRepeat) {
                isRepeat = true;
                if (errorCode == PrinterBinder.PRINTER_ERROR_NO_PAPER) {
                    mHandler.sendMessage(mHandler.obtainMessage(2, detail));
                } else {
                    ToastUtils.showCustom(frmCtx, detail + "--" + errorCode);
                }
            }
        }
    }

}
